package biz

import (
	"context"
	"fmt"
	"github.com/duke-git/lancet/convertor"

	v1 "kratosMiddleware/api/helloworld/v1"

	"github.com/go-kratos/kratos/v2/errors"
	"github.com/go-kratos/kratos/v2/log"
)

var (
	// ErrUserNotFound is user not found.
	ErrUserNotFound = errors.NotFound(v1.ErrorReason_USER_NOT_FOUND.String(), "user not found")
)

// Greeter is a Greeter model.
type Greeter struct {
	Hello string
}

// GreeterRepo is a Greater repo.
type GreeterRepo interface {
	Save(context.Context, *Greeter) (*Greeter, error)
}

// GreeterUsecase is a Greeter usecase.
type GreeterUsecase struct {
	repo GreeterRepo
	log  *log.Helper
}

// NewGreeterUsecase new a Greeter usecase.
func NewGreeterUsecase(repo GreeterRepo, logger log.Logger) *GreeterUsecase {
	return &GreeterUsecase{repo: repo, log: log.NewHelper(logger)}
}

// Notice 登陆这里应该设置一下redis中token的，我这里就省略了，主要用来演示白名单的～
func (uc *GreeterUsecase) Login(ctx context.Context, req *v1.Empty) (*v1.LoginReply, error) {

	reply := &v1.LoginReply{}
	reply.Msg = "哈哈，登陆了！"

	return reply, nil
}

func (uc *GreeterUsecase) CreateGreeter(ctx context.Context, g *Greeter) (*Greeter, error) {
	uc.log.WithContext(ctx).Infof("CreateGreeter: %v", g.Hello)

	// 从ctx中获取uid，简单写法
	uid := getUserIDFromCtx(ctx)
	if uid == 0 {
		return nil, errors.New(400, "invalid userId", "获取用户Id失败！")
	}
	fmt.Printf("uid %d 成功调用了接口! \n", uid)

	return uc.repo.Save(ctx, g)
}

func getUserIDFromCtx(ctx context.Context) int64 {
	uid, err := convertor.ToInt(ctx.Value("uid"))
	if err != nil {
		return 0
	}
	return uid
}
